<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/8
 * Time: 11:10
 */

namespace common\service;
use common\models\ProxySonAgent;
use common\models\Trade;
use common\models\User;
use common\models\UserAccount;
use yii\data\Pagination;
use common\models\ProxyAlso;
use common\models\ProxyBroker;
use yii\helpers\ArrayHelper;

//用户处理类

class UserService extends BaseService
{
    //常量配置 - 用户状态
    const STATUS_NOTACTIVE = 0; //未激活用户
    const STATUS_ACTIVE = 1;    //已激活用户
    const STATUS_FREEZE = 2;    //已冻结用户
    const STATUS_DELETED = 3;   //已删除用户

    //常量配置 - 用户类型
    const REAL_ROLE = 1;        //真实用户
    const MONI_ROLE = 2;        //模拟用户

    //常量配置 - 用户等级
    const NO_PAY   = 1;         //未注资
    const LOWER_MEMBER  = 2;    //初级会员
    const HIGHER_MEMBER = 3;    //高级会员
    const BEST_MEMBER   = 4;    //至尊会员

    //用户类型
    // 客户类型：1客户  2门店  3县级代理  4市级代理  5省级代理
    const USER_TYPE_LIST = [
          1 => '客户',
          2 => '门店',
          3 => '县级代理',
          4 => '市级代理',
          5 => '省级代理',
    ];


    //获取用户状态
    public static function getStatusText($status)
    {
        switch($status)
        {
            case self::STATUS_NOTACTIVE:
                return '未激活';
                break;
            case self::STATUS_ACTIVE:
                return '已激活';
                break;
            case self::STATUS_FREEZE:
                return '已冻结';
                break;
            case self::STATUS_DELETED:
                return '已删除';
                break;
        }
    }


    /**
     *  递归获取所有下级用户
     */
    /**
     * [getTree 根据父ID 遍历除所有子集]
     * @param  integer $parentid 父ID
     * @param  array   $array    查找数组
     * @param  integer $level    当前等级
     * @return array
     */
    public static function getSonTree($parentid = 0, $array = array())
    {
        $newarray  = array();
        $temparray = array();
        foreach ( $array as $v )
        {
            if ($v['int_id'] == $parentid)
            {
                $newarray[] = $v;
                $temparray = self::getSonTree($v['id'], $array);
                if ($temparray)
                {
                    $newarray = array_merge ($newarray, $temparray);
                }
            }
        }
        return $newarray;
    }

    /**
     * @desc  代理层级下拉列表
     * @param $pid 代理id
     */
    public static function proxytree($pid,$seleted_pid='')
    {
        $son =  self::getUserList($pid);
        $son[$pid]['int_id'] = 0;

        $underson = self::getUnderSon($pid,$son);
        if($underson){
            foreach ($underson as $v){
                $son = array_merge($son,$v);
            }
        }

        if(count($son)>1){
            $tree_list = TreeService::makeTreeForHtml($son);
            if(empty($seleted_pid)){
                $select ='<option value="" selected>--选择推荐人--</option>';
            }else{
                $select ='<option value="">--选择推荐人--</option>';
            }

            foreach($tree_list as $val){
                if($val['id']==$pid)
                {
                    if($val['id'] == $seleted_pid){
                        $select .= '<option value="'.$val['id'].'" selected>';
                    }else{
                        $select .= '<option value="'.$val['id'].'">';
                    }

                }else{

                    if($val['id'] == $seleted_pid){
                        $select .= '<option value="'.$val['id'].'" selected>';
                    }else{
                        $select .= '<option value="'.$val['id'].'">';
                    }

                }
                $select .= str_repeat('— ',$val['level']);
                $select .= $val['name'];
                $select .= '</option>';
            }

        }else{

            $select ='<option value="">--选择推荐人--</option>';

        }

        return $select;
    }

    /**
     *  获取所有用户列表
     */
    public static function getUserList($int_id = '',$condition='')
    {
        $query = User::find();
        if(!empty($int_id) && $int_id>0)
        {
            $query->where('id = :pid or int_id = :pid',[':pid'=>$int_id]);
        }

        if(!empty($condition)){
            $query->andWhere($condition);
        }

        return $query->select(['id','name','int_id'])->indexBy('id')->asArray()->all();
    }

    /**
     * @desc 代理层级下级所有子代理数据
     * @param $pid 代理id
     */
    public static function getSonUserList($pid)
    {
        $son =  self::getUserList($pid);
        $underson = self::getUnderSon($pid,$son);
        if($underson){
            foreach ($underson as $v){
                $son = array_merge($son,$v);
            }
        }
        return $son;
    }

    /**
     * 获取子代理的子代理
     *
     */
    public static function getUnderSon($id,$data)
    {
        $newarray  = array();
        $temparray = array();
        foreach ($data as $v){
            if($id!=$v['id']){
                $son = self::getUserList($v['id']);
                if($son){
                    $newarray[] = $son;
                    $temparray = self::getUnderSon($v['id'],$son);
                    if($temparray){
                        $newarray = array_merge($newarray, $temparray);
                    }
                }
            }
        }
        return $newarray;
    }

    /**
     * $desc 根据pid获取代理层级所有子代理的uid集合
     * @param $pid 代理id
     */
    public static function getSonCustomerUids($pid)
    {
        $list = self::getSonUserList($pid);
        $pids = ArrayHelper::getColumn($list,'id');
        $uids = [];
        if(!empty($pids)){
            $user_list = User::find()->where(['in','pid',$pids])->asArray()->all();
            $uids = ArrayHelper::getColumn($user_list,'id');
        }
        return $uids;
    }

    /**
     * $desc 根据pid获取代理层级所有子代理的uid集合
     * @param $pid 代理id
     */
    public static function getSonCustomerMt4s($pid)
    {
        $uids = self::getSonCustomerUids($pid);
        $accounts_list = UserAccount::find()->where(['in','uid',$uids])->asArray()->all();
        $mt4s = ArrayHelper::getColumn($accounts_list,'account');
        return $mt4s;
    }

    /**
     * 名下客户下拉列表
     */
    public static function getSonCustomerList($pid,$uid='')
    {
        $uids = self::getSonCustomerUids($pid);
        if(!empty($uids)){
            $user_list = User::find()->where(['in','id',$uids])->asArray()->all();
        }

        if(count($user_list)>1){
            if(!empty($uid)){
                $select ='<option value="">--选择用户--</option>';
            }else{
                $select ='<option value="" selected>--选择用户--</option>';
            }

            foreach($user_list as $val){
                if($val['id']==$uid){
                    $select .= '<option value="'.$val['id'].'"  selected>';
                }else{
                    $select .= '<option value="'.$val['id'].'">';
                }
                $select .= $val['sur'].$val['name'];
                $select .= '</option>';
            }

        }else{
            $select ='<option value="">--选择用户--</option>';
        }

        return $select;
    }

    //获取用户列表 id=>name 键值对方法
    public static function getList()
    {
        $list = User::find()->select(['id','sur','name'])->asArray()->indexBy('id')->all();
        foreach($list as $key=>$val)
        {
            $list[$key] = $val['sur'].$val['name'];
        }
        return $list;
    }


    /**
     *  检测填写的推荐人是否合法
     */
    public static function CheckIntCode($int_code,$uid)
    {
        //获取推荐人列表
        $int_list = self::getIntList();

        //根据填写的推荐人手机号判断是否存在用户
        $user = User::find()->where(['phone'=>$int_code])->asArray()->one();
        if(!$user){
            return false;
        }

        //判断是否存在上级父类用户
        if(isset($int_list[$user['id']]['intparent'])){
            //若存在推荐人,判断当前用户是否在里面
            if(!in_array($uid,$int_list[$user['id']]['intparent'])){
                return true;
            }else{
                return false;
            }
        }else{
            //不存在,可以设置为推荐人
            return true;
        }
    }


    /**
     *  获取推荐列表数据
     */
    public static function getIntList()
    {
        //取得所有有推荐号的会员
        $has_int_code = User::find()->where('int_id>0')->indexBy('id')->asArray()->all();
        $has_int_code = self::intcode($has_int_code);
        return $has_int_code;
    }

    /**\
     * @param $proxyUser
     * @return mixed
     * @descr 获取上级推荐人
     */
    public static function intcode($User)
    {
        foreach ($User as $k=>$v)
        {
            $intparent = array();
            if($v['int_id']>0){ //有推荐人
                $intparent[] = $v['int_id'];
                $parent_id = self::getIntId($v['int_id'],$User);//上级门店还有门店
                if($parent_id){
                    $intparent = array_merge($intparent,$parent_id);
                }
            }
            $User[$k]['intparent'] = $intparent;
        }
        return $User;
    }

    /**
     * @param $pid
     * @param $proxyUser
     * @return array
     * @descr 根据shopid遍历所有上级门店
     */
    public static function getIntId($intid,$proxyUser)
    {
        $newintid = array();
        $temp = array();
        if($proxyUser[$intid]['id'] == $intid && $proxyUser[$intid]['int_id']>0) //还有上级推荐人
        {
            $newintid[] =  $proxyUser[$intid]['int_id'];
            $temp = self::getIntId($proxyUser[$intid]['int_id'],$proxyUser);//递归遍历
            if($temp){
                $newintid = array_merge($newintid, $temp);
            }
        }
        return $newintid;
    }


}
